<?php
namespace app\push\controller;
use think\worker\Server;
use think\Db;
class Worker extends Server
{
    protected $socket = 'websocket://0.0.0.0:2000';
    /**
     * 收到信息
     * @param $connection
     * @param $data
     */
    public function onMessage($connection, $data)
    {
        $connection->lastMessageTime = time();
        $info = json_decode($data,true);
        if (!isset($connection->uid)) {
            // 没验证的话把第一个包当做uid（这里为了方便演示，没做真正的验证）
            if (!empty($info)) {
                $user_id = M('UserToken')->getUserIdByAccessToken($info['access_token']);
                $connection->uid = $user_id;
                $this->uidConnections[$info['id']][$connection->uid] = $connection;
            }else {
            }
        }else {

            foreach($this->uidConnections[$info['id']] as $val)
            {
                if ($val->uid !=  $connection->uid) {
                    $val->send($data);
                }
            }
        }
    }
    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
    }
    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {
       $connection->send('close');
    }
    /*** 当客户端的连接上发生错误时触发* @param $connection* @param $code* @param $msg*/
    public function onError($connection, $code, $msg){
        echo "error $code $msg\n";
    }
    /*** 每个进程启动* @param $worker*/
    public function onWorkerStart($worker){
        \Workerman\Lib\Timer::add(1, function()use($worker){
            $time_now = time();
            foreach($worker->connections as $connection) {
                // 有可能该connection还没收到过消息，则lastMessageTime设置为当前时间
                if (empty($connection->lastMessageTime)) {
                    $connection->lastMessageTime = $time_now;
                    continue;
                }
                // 上次通讯时间间隔大于心跳间隔，则认为客户端已经下线，关闭连接
                if ($time_now - $connection->lastMessageTime > 60) {
                    $connection->close();
                }
            }
        });
    }

}